package com.android.clinic.doctors.app.ui.inquiry.view;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.android.clinic.doctors.app.R;
import com.android.clinic.doctors.app.entity.ImageViewInfo;
import com.android.clinic.doctors.app.glide.ImageLoaderUtils;
import com.android.clinic.doctors.app.ui.widget.GridViewWrapper;
import com.android.clinic.doctors.app.utils.DisplayUtil;
import com.android.clinic.doctors.app.utils.LocalDataUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by cheng on 2018/6/26.
 */
public class PageImageView extends LinearLayout {

    private Context mContext;
    private ViewPager mViewPager;
    private LinearLayout layPageIndex;
    private PageIndicatorView mPageIndicatorView;

    private List<GridImageViewAdapter> adapterList = new ArrayList<>();
    private List<GridView> mGridViews = new ArrayList<>();
    private ArrayList<ImageViewInfo> imageInfoList = new ArrayList<>();
    private Map<Integer, Map<Integer, ImageView>> imageMaps = new LinkedHashMap<>();

    private int currentPage;
    private int pageNo = 0;
    public static int pageSize = 3; // 每页显示数量
    private int columns = 1;
    private List<Map> dataList = new ArrayList<>();

    private OnTouchListener onTouchViewListener;

    public PageImageView(Context context) {
        super(context);
        mContext = context;
    }

    public PageImageView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public PageImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public void initView(Context context, int pageSize, int columns) {
        mContext = context;
        this.pageSize = pageSize;
        this.columns = columns;

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(DisplayUtil.getScreenWidth() - DisplayUtil.dip2px(80),
                (DisplayUtil.getScreenWidth() / columns)- DisplayUtil.dip2px(40));
        layPageIndex = findViewById(R.id.layout_index);
        mViewPager = findViewById(R.id.viewPager);
        mViewPager.setOffscreenPageLimit(0);
        mViewPager.setPadding(0, 0, 0, 0);
        mViewPager.setLayoutParams(params);
    }

    public void initData(int position) {
        if (imageInfoList.size() == 0) {
            new ParesDataThread(position).start();
        }
    }

    private class ParesDataThread extends Thread {

        int position = 0;

        private ParesDataThread(int position) {
            this.position = position;
        }

        @Override
        public void run() {
            // 获取数据
            imageInfoList = (ArrayList<ImageViewInfo>) LocalDataUtils.objectMap.get(position);
            handler.sendEmptyMessage(0);
        }
    }

    private Handler handler = new Handler() {

        @SuppressWarnings("deprecation")
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (null != imageInfoList && imageInfoList.size() > 0) {
                int labelSize = imageInfoList.size();
                dataList.clear();
                for (int i = 0; i < labelSize ; i++) {
                    Map map = new HashMap();
                    map.put("imgUrl", imageInfoList.get(i).getImgUrl());
                    dataList.add(map);
                }
                // 计算页数
                int listSize = dataList.size();
                if (listSize % pageSize != 0) {
                    pageNo = (listSize / pageSize) + 1;
                } else {
                    pageNo = (listSize / pageSize);
                }
                mGridViews.clear();
                adapterList.clear();
            }

            for (int j = 0; j < pageNo; j++) {
                Map<Integer, ImageView> map = new LinkedHashMap<>();
                GridViewWrapper appPage = new GridViewWrapper(mContext);
                appPage.setSelector(new ColorDrawable(Color.TRANSPARENT));
                GridImageViewAdapter adapter = new GridImageViewAdapter(mContext, dataList, j);
                adapterList.add(adapter);
                appPage.setAdapter(adapter);
                appPage.setNumColumns(columns);
                mGridViews.add(appPage);
                imageMaps.put(j, map);
            }

            if (pageNo > 1) {
                layPageIndex.removeAllViews();
                mPageIndicatorView = new PageIndicatorView(mContext, layPageIndex, mPageIndicatorView.TYPE_IMAGE);
                mPageIndicatorView.setCount(mGridViews.size());
                mPageIndicatorView.setImageResource(android.R.drawable.presence_online, android.R.drawable.presence_invisible);
                mPageIndicatorView.initView();
            } else {
                layPageIndex.setVisibility(View.GONE);
            }

            GridViewPagerAdapter pagerAdapter = new GridViewPagerAdapter();
            mViewPager.setAdapter(pagerAdapter);
            mViewPager.setCurrentItem(0);
            mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener(){

                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                }

                @Override
                public void onPageSelected(int position) {
                    currentPage = position;
                    mPageIndicatorView.selectedViewIndex(currentPage);
                }

                @Override
                public void onPageScrollStateChanged(int state) {

                }
            });

            if (null != onTouchViewListener) {
                mViewPager.setOnTouchListener(onTouchViewListener);
            }
        }
    };

    private class GridImageViewAdapter extends BaseAdapter {

        private LayoutInflater inflater;
        private List<Map> mList = new ArrayList<>();

        private GridImageViewAdapter(Context context, List<Map> list, int page) {
            inflater = LayoutInflater.from(context);
            int i = page * pageSize;
            int end = i + pageSize;
            while ((i < list.size()) && (i < end)) {
                mList.add(list.get(i));
                i++;
            }
        }

        @Override
        public int getCount() {
            return mList.size();
        }

        @Override
        public Object getItem(int position) {
            return mList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (null == convertView) {
                convertView =  inflater.inflate(R.layout.item_inquiry_grid, null);
                holder = new ViewHolder();
                holder.ivPage = convertView.findViewById(R.id.iv_page);
                if (onTouchViewListener != null) {
                    holder.ivPage.setOnTouchListener(onTouchViewListener);
                }
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            Map imageViewInfo = mList.get(position);
            if (null != imageViewInfo) {
                ImageLoaderUtils.getInstance().loadNormalImage(imageViewInfo.get("imgUrl").toString(), holder.ivPage);
                imageMaps.get(currentPage).put(position, holder.ivPage);
            }
            return convertView;
        }

        class ViewHolder {
            ImageView ivPage;
        }
    }

    private class GridViewPagerAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return mGridViews.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == (object);
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView(mGridViews.get(position));
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            container.addView(mGridViews.get(position), 0);
            return mGridViews.get(position);
        }
    }

}
